<template>
  <a-dropdown
    :visible="show"
    overlay-class-name="header-btn-item msg-notice-box"
    :trigger="['click']"
    :overlay-style="{ zIndex: '2000!important' }"
  >
    <div slot="overlay">
    <a-modal
    v-if="false"
      v-model="standScoreVisiable"
      :mask-closable="false"
      title=""
      :width="750"
      centered
      :dialog-style="{ height: '380px' }"
      class="rt-i-modal"
      :confirm-loading="getStandScoreListLoading"
      @ok="standScoreSave"
    >
      <span
        slot="closeIcon"
        class="c-dialog-close-icon"
      ><a-icon
        :component="require('@/assets/icon/close.svg')"
      /></span>

      <div class="c-dialog-title fw-500">全局维护</div>

      <div slot="footer">
       
        <div class="d-flex jc-end mr-8">
           <a-button
            type="primary"
            @click="$router.push('/ringstone')"
          >铃声列表</a-button>
          <a-button
            type="primary"
            :loading="getStandScoreListLoading"
            @click="standScoreSave"
          >保存</a-button>
        </div>
      </div>
      <a-form-model
        ref="addForm"
        :model="addGlobalForm"
        class="ecm-qj-box d-flex flex-column"
      >
        <!-- 按照低中高排序，通过css 修改样式的排序 -->

        <template v-for="(it, i) in 3">
          <a-row :key="i" :class="`ecm-qj-item-${i}`">
            <a-col :span="10">
              <a-form-model-item
                v-for="(item, index) in priorityList"
                v-if="i === index"
                :key="item.value"
                :prop="`score${index}`"
              >
                <a-icon
                  :component="item.icon"
                  style="font-size:28px;vertical-align: middle;"
                />
                {{ item.name }}

                <a-input-number
                  disabled
                  v-if="standScoreListF[index]"
                  :value="standScoreListF[index].score"
                  class="ecm-qj-item-iput input-type-o"
                  :min="0"
                  :max="
                    standScoreListF[index + 1]
                      ? standScoreListF[index + 1].score - 1
                      : Infinity
                  "
                  @change="e => changeStandScoreList(e, index)"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <template v-for="(v1, i1) in 3">
                <template v-if="i === i1">
                  <a-checkbox
                    v-if="standScoreListF[i1]"
                    :key="i1"
                    :checked="standScoreListF[i1].silence != 0"
                    @change="onChange($event, i1)"
                  >
                    静默
                  </a-checkbox>
                </template>
              </template>
            </a-col>
            <a-col :span="10">
              <template v-for="(v1, i1) in 3">
                <template v-if="i === i1">
                  <a-select
                    v-if="standScoreListF[i1]"
                    :key="i1"
                    v-model="standScoreListF[i1].ringstone"
                  >
                    <a-select-option
                      key="1"
                      value="alert1"
                    >警报1</a-select-option>
                    <a-select-option
                      key="2"
                      value="alert2"
                    >警报2</a-select-option>
                    <a-select-option
                      key="3"
                      value="alert3"
                    >警报3</a-select-option>
                    <a-select-option
                      key="4"
                      value="alert4"
                    >警报4</a-select-option>
                    <template v-for="val in rsList">
                         <a-select-option
                          :key="val.id"
                          :value="val.id"
                        >{{val.fileName}}</a-select-option>
                    </template>
                  </a-select>
                </template>
              </template>
            </a-col>
          </a-row>
        </template>
      </a-form-model>
    </a-modal>
      <a-spin :spinning="noticeLoading" class="c-notice-box">
        <div class="dropdown-tabs" :style="{ width: '297px' }">
          <div class="fs-16 fw-500 pt-16 pl-16 pb-12 text-color-21252e ">
            消息通知
          </div>
          <a-list>
            <RecycleScroller
              v-if="noticeList.length > 0"
              :item-size="55"
              class="msg-list-box"
              :items="noticeList"
              key-field="id"
            >
              <a-list-item
                slot-scope="{ item, index }"
                class="cu-pointer"
                @click="itemClick(item, index)"
              >
                <a-list-item-meta>
                  <span slot="title" :title="item.description">
                    <span v-if="item.read === 0" class="notice-dot-icon" />
                    <span>{{ item.description }}</span>
                    <!-- <span class="ml-6">{{ item.code }}</span> -->
                  </span>
                  <span slot="description">
                    <span>on {{ item.tailNumber }} Arrived at
                      {{ item.arr || '--' }}</span>
                  </span>
                  <noticePriorityIcon
                    slot="avatar"
                    :priority="item.priority"
                    :msg-type="item.name"
                  />
                </a-list-item-meta>
                <div class="fs-12 text-c msg-po color-s">
                  {{ forTime(item.msgTime) }}
                </div>
              </a-list-item>
            </RecycleScroller>
          </a-list>
          <a-divider class=" msg-divider" />
          <div class="d-flex jc-end">
            <a-button class="mr-8 mb-16" @click="show = false">关闭</a-button>
            <a-button
              :loading="readLoading"
              :disabled="noticeNum === 0"
              class="mr-8 mb-16"
              type="primary"
              @click="readAllHandler"
            >全部标为已读</a-button>
            <a-button
              :disabled="noticeList.length === 0"
              :loading="readLoading"
              class="mr-16 mb-16"
              type="primary"
              @click="removeMessageHandler"
            >清除已读</a-button>
          </div>
        </div>

        <div class="msg-filter-btn">
          <!-- 筛选 -->
          <a-popover
            overlay-class-name="msg-filter-box"
            title="筛选条件"
            :visible="checkedFilterShow"
            trigger="click"
            placement="bottomRight"
            :get-popup-container="
              triggerNode => {
                return triggerNode.parentNode || document.body;
              }
            "
            @visibleChange="handleClickChange"
          >
            <template slot="content">
              <a-checkbox-group v-model="checkedFilterTmp">
                <a-row class="checked-filter-box">
                  <a-col
                    v-for="item in filterList"
                    :key="item.label"
                    class="notice-item-e"
                    :span="24"
                  >
                    <a-checkbox :value="item.value">
                      {{ item.label }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
              <a-divider />
                <a-row  >
                  <a-col :span="24" v-if="standScoreListF&&standScoreListF.length>0">
                    <template v-for="(v,i) in 3">
                     <a-checkbox  @change="change_silence($event,i)"  :checked="standScoreListF[i].silence != 0" style="margin-left:0;margin-bottom:14px"  v-if="i==0" :key="v">低优先级静音</a-checkbox>
                      <a-checkbox @change="change_silence($event,i)" :checked="standScoreListF[i].silence != 0" style="margin-left:0;margin-bottom:14px" v-if="i==1" :key="v">中优先级静音</a-checkbox>
                      <a-checkbox @change="change_silence($event,i)" :checked="standScoreListF[i].silence != 0" style="margin-left:0;" v-if="i==2" :key="v">高优先级静音</a-checkbox>                 
                    </template>
                  </a-col>
                </a-row>
                <a-divider class="mt-12 mb-12" />
              <div class="d-flex jc-center">
                <a-button
                  size="small"
                  @click="handleClickChange(false)"
                >取消</a-button>
                <a-button
                  size="small"
                  type="primary"
                  @click="filterChangeSave"
                >保存</a-button>
              </div>
            </template>
            <a-tooltip title="筛选" placement="bottomRight">
              <a-button type="link">
                <a-icon :component="require('@/assets/icon/FilterNew.svg')" />
              </a-button>
            </a-tooltip>
          </a-popover>
        </div>
      </a-spin>
    </div>
    <span class="header-notice" @click="fetchNotice">
      <a-badge class="notice-badge" :count="noticeNum">
        <a-icon
          :component="require('@/assets/icon/Message_Center.svg')"
          style="font-size:16px"
          class="msg-tips-ani"
        />
      </a-badge>
    </span>
  </a-dropdown>
</template>

<script>
import { priorityList, isNotOption } from '@/pages/common/constant.js';
import { getRingstoneList } from '@/services/user'
// ______________________
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex';
import { format } from 'timeago.js';
import { RecycleScroller } from 'vue-virtual-scroller';

export default {
  name: 'HeaderNoticeTips',
  components: {
    RecycleScroller
  },
  data() {
    return {
      standScoreListFb:null,
      rsList:[],
       addGlobalForm: {},
      priorityList,
       standScoreVisiable: false,
      //  _______________________
      checkedFilterShow: false,
      checkedFilterTmp: [],
      checkedFilter: [1, 2, 3],
      show: false,
      timeHandler: -1,
      getMsgListFlag: -1,
      alarmFlag: -1,
      format,
      filterList: Object.freeze([
        {
          value: 3,
          label: '显示高优先级'
        },
        {
          value: 2,
          label: '显示中优先级'
        },
        {
          value: 1,
          label: '显示低优先级'
        }
        // {
        //   value: 0,
        //   label: '无登记'
        // }
      ])
    };
  },
  computed: {
    ...mapState('user', [
      'noticeLoading',
      'noticeList',
      // 'noticeNum',
      'readLoading',
    ]),
    ...mapGetters('user', ['userInfo']),
     ...mapState('eventCodeMaintenance', [
      'getStandScoreListLoading',
      'standScoreList', 
    ]),
    standScoreListF() {
      return [...this.standScoreList].sort((a, b) => a.priority - b.priority);
    },
    noticeNum() {
      return this.noticeList.reduce((a, b) => {
        return a + ((b.read + 1) % 2);
      }, 0);
    }
  },
  watch: {
    show(nv) {
      // if (!nv) {
      //   clearTimeout(this.getMsgListFlag);
      //   clearTimeout(this.alarmFlag);
      // }
      if(nv){
        this.getStandScoreList()
      }
    },
    noticeNum(nv, ov) {
      if (nv && nv > ov) {
        setTimeout(() => {
          this.alarmAc();
        }, 0);
      }
    }
  },
  created(){
    getRingstoneList().then(res=>{
      this.rsList = res.data
    })
  },
  mounted() {
    // this.getMSGNumHandler();
    this.getMsgList();
  },
  beforeDestroy() {
    clearTimeout(this.timeHandler);
    clearTimeout(this.alarmFlag);
    clearTimeout(this.getMsgListFlag);
  },
  inject: ['adminLayout'],
  methods: {
    ...mapActions('eventCodeMaintenance', [
      'getStandScoreList',
      'standScoreUpdate',
    ]),
    change_silence(e,i){
      if(e.target.checked){
        this.standScoreListF[i].silence =1+''
      }else{
         this.standScoreListF[i].silence =0+''
      }
    },
    open(){
    this.standScoreVisiable=true
    this.getStandScoreList()
    },
     onChange(e, i) {
      this.standScoreListF[i]['silence'] = e.target.checked ? '1' : '0';
    },
      // 保存全局维护
    standScoreSave() {
      this.standScoreUpdate({
       userId:this.userInfo.userId,
       scoreData: this.standScoreList,
       scoreType:1+''
      }).then(res => {
        if (res) {
          this.standScoreVisiable = false;
        }
      }).catch(()=>{
         this.standScoreVisiable = false;
        this.$message.warning('保存失败')
      })
    },
    ...mapActions('user', [
      'getMessageListByUserId',
      'getMessageDetail',
      // 'getMessageNumByUserId',
      'modifyByRead',
      'removeMessage'
    ]),

    ...mapMutations('fraMonitoring', ['setState']),
    // async getMSGNumHandler() {
    //   this.getMessageNumByUserId({ userId: this.userInfo.userId });

    //   this.timeHandler = setTimeout(() => {
    //     this.getMSGNumHandler();
    //   }, 60000);
    // },
    itemClick(record, index) {
      this.$store.commit('eventMonitoring/setState', {
        key: 'dataType',
        payload: 2
      });
      this.$store.commit('eventMonitoring/setState', {
        key: 'dataTypeIndex',
        payload: [index]
      });
      record.read = 1;
      const params = {
        id: record.id,
        isAll: 0,
        userId: this.userInfo.userId
      };
      this.modifyByRead(params);
      this.setState({ key: 'eventDetailsVisible', payload: true });
      const currentRow = {
        ...record,
        tailnumber: record.tailNumber,
        id: record.eventId,
        event: { ...record, id: record.eventId, tailnumber: record.tailNumber }
      };
      localStorage.setItem('eRow', JSON.stringify(currentRow));
    },
    // 筛选弹框
    handleClickChange(visible) {
      if (visible) {
        this.checkedFilterTmp = [...this.checkedFilter];
        this.standScoreListFb = JSON.parse(JSON.stringify(this.standScoreListF))
      }
      if(!visible){
       console.log(this.standScoreListFb)
       this.standScoreListFb.forEach((v,i)=>{
          this.standScoreListF[i]['silence']=v['silence']
       })
      }
      this.checkedFilterShow = visible;
    },
    // 保存选择的筛选条件
    filterChangeSave() {
      this.checkedFilterShow = false;
      this.checkedFilter = [...this.checkedFilterTmp];
      this.getMsg();
      // 保存是否静音
      this.standScoreSave()
    },
    forTime(time) {
      return this.$moment
        .utc(new Date())
        .diff(this.$moment.utc(time), 'minute') < 60
        ? format(
          this.$moment
            .utc(time)
            .add(8, 'hour')
            .format('YYYY-MM-DD HH:mm:ss'),
          'zh_CN'
        )
        : time;
    },
    // 获取用户消息列表
    async getMsg(noLoading = false) {
      const params = {
        priority: this.checkedFilter,
        userId: this.userInfo.userId,
        noLoading
      };
      await this.getMessageListByUserId(params);
    },
    // 全部已读
    readAllHandler() {
      const params = {
        userId: this.userInfo.userId,
        isAll: 1
      };
      this.modifyByRead(params).then(res => {
        if (res) {
          this.getMsg();
        }
      });
    },
    // 清除
    removeMessageHandler() {
      const params = {
        userId: this.userInfo.userId,
        isAll: 1
      };
      this.removeMessage(params).then(res => {
        if (res) {
          this.getMsg();
        }
      });
    },
    // 提示音
    alarmHandler() {
      if (this.noticeList?.findIndex(item => item.read === 0) >= 0 ?? 0) {
        const name = document.querySelector('.msg-tips-ani').style
          .animationName;
        document.querySelector('.msg-tips-ani').style.animationName =
          name === 'upAnimation2' ? 'upAnimation' : 'upAnimation2';
        // this.alarmAc();
      }

      this.alarmFlag = setTimeout(() => {
        this.alarmHandler();
        this.adminLayout.myplay();
      }, 30000);
    },

    alarmAc() {
      if (this.$route.name !== '机队监控') {
        this.$store.dispatch('setting/messageAudioHandler',this.userInfo.userId);
      }
    },
    async getMsgList() {
      clearTimeout(this.getMsgListFlag);
      await this.getMsg(true);
      if (this.alarmFlag < 0) {
        this.alarmHandler();
      }
      this.getMsgListFlag = setTimeout(() => {
        this.getMsgList();
        this.alarmAc();
      }, 5000);
    },
    async fetchNotice() {
      if (!this.show) {
        this.show = true;
      }
      // this.getMsgList();
    }
  }
};
</script>

<style lang="less">
@import './header-btn.less';
.msg-notice-box {
  .dropdown-tabs {
    display: flex;
    flex-direction: column;
  }
  .ant-list.ant-list-split {
    flex: 1;
  }
  .ant-list-item-meta-avatar {
    padding-left: 6px;
    font-size: 14px;
    width: 36px;
  }
}

.notice-dot-icon {
  position: absolute;
  width: 7px;
  height: 7px;
  background: @c-red;
  left: 39px;
  top: 13px;
  border-radius: 100%;
}
.msg-tips-ani {
  transform-origin: center top;
  animation-duration: 2s;
  animation-fill-mode: both;
  animation-iteration-count: 1;
  animation-delay: 0.2s;
}
@keyframes upAnimation {
  0% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  10% {
    transform: rotate(-12deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  20% {
    transform: rotate(12deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  28% {
    transform: rotate(-10deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  36% {
    transform: rotate(10deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  42% {
    transform: rotate(-8deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  48% {
    transform: rotate(8deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  52% {
    transform: rotate(-4deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  56% {
    transform: rotate(4deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  60% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  100% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
}
@keyframes upAnimation2 {
  0% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  10% {
    transform: rotate(-12deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  20% {
    transform: rotate(12deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  28% {
    transform: rotate(-10deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  36% {
    transform: rotate(10deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  42% {
    transform: rotate(-8deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  48% {
    transform: rotate(8deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  52% {
    transform: rotate(-4deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  56% {
    transform: rotate(4deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  60% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.755, 0.5, 0.855, 0.06);
  }
  100% {
    transform: rotate(0deg);
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
}
</style>
